package com.example.Interceptor;

import com.alibaba.fastjson.JSON;
import com.example.utils.BaseContext;
import com.example.utils.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    //拦截请求处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session对象
        HttpSession session = request.getSession();
        //获取到储存到session中的数据
        Object employee = session.getAttribute("employee");
        Object userid = session.getAttribute("user");
        //将在session中获取的数据存储到线程副本中
        String ajaxHeader = request.getHeader("X-Requested-With");//获取ajax参数
        //判断session中是否有数据
        if (employee != null) {
            BaseContext.setById((Long) employee);
            return true;
        }
        if (userid != null) {
            BaseContext.setById((Long) userid);
            return true;
        }
        if ("XMLHttpRequest".equals(ajaxHeader)) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset:utf-8");
            PrintWriter out = response.getWriter();
            out.write("{\"code\":0,\"msg\":\"您登录已过期\"}");//json数据
            out.flush();
            out.close();
        }
        //响应页面结果
        response.getWriter().write(JSON.toJSONString(new R(0, "NOTLOGIN")));
        return false;
    }
}
